import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import { Row, Col, Card, Icon, Button, Popconfirm, message, Divider, Form, Select, Input, Table} from "antd";
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { Option } = Select;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


@connect(({ path, global, loading }) => ({
  selectSource:global.selectSource,
  resdata: path.resdata,
  loading: path.loading.reslist,
  // loading: loading.models.path,
}))
@Form.create()
export default class SparesChoose extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 5,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { dispatch } = this.props;
    const { pageSize } = this.state;
    // 养护人
    dispatch({
      type: 'global/fetch_select_creator',
    });
    // 列表
    this.getDataList({},pageSize,1);
  }

  componentWillReceiveProps(nextProps) {
    // console.log('maintenanceId',nextProps)
    if (nextProps.maintenanceId != this.props.maintenanceId) {

      this.getDataList({},pageSize,1);
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, maintenanceId} = this.props;
    maintenanceId && dispatch({
      type: 'path/fetch_path_list',
      payload: {
        ...params,
        pageSize,
        currentPage,
        maintenanceId
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  // handleSelectRows = rows => {
  //   this.setState({
  //     selectedRows: rows.map(item => item.devId),
  //   });
  // };

  handleSelectRows = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRows: selectedRowKeys,
    },()=>{
      this.props.selectCallBack(selectedRowKeys);
    });
  };


  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };


  // 搜索内容
  renderSearchForm() {
    const { form, selectSource} = this.props;
    const { getFieldDecorator } = form;
    const { selectedRows } = this.state;

    // console.log(selectedRows)


    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24} style={{paddingRight:0}}>
            <FormItem label="路线编号">
              {getFieldDecorator('lineCode',{
              })(<Input placeholder="请输入路线编号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24} style={{paddingRight:0}}>
            <FormItem label="路线名称">
              {getFieldDecorator('lineName',{
              })(<Input placeholder="请输入路线名称" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24} style={{paddingRight:0}}>
            <FormItem label="编制人">
              {getFieldDecorator('user_id',{
              })(
                <Select placeholder="编制人"   style={{ width: '100%' }}>
                  {selectSource.userlist && selectSource.userlist.map(item => (
                    <Option key={item.userId} value={item.username}>{item.username}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24} >
            <div >
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, spareChoose } = this.props;
    const { selectedRows } = this.state;


    const columns = [
      {
        title: '路线编号',
        dataIndex: 'lineCode',
      },
      {
        title: '路线名称',
        dataIndex: 'lineName',
      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',
      },
      {
        title: '备注',
        dataIndex: 'remarks',
      },
      {
        title: '编制人',
        dataIndex: 'creatorName',
      },
    ];



    const rowSelection = {
      // selectedRowKeys:spareChoose,
      onChange: this.handleSelectRows,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };


    return (
      <Card bordered={false} bodyStyle={{padding:0}}>
        <div className={styles.tableList}>
          <div className={styles.tableListSelectForm}>{this.renderSearchForm()}</div>
          <Table
            columns={columns}
            dataSource={resdata.list ? resdata.list : []}
            pagination={resdata.pagination}
            rowSelection={rowSelection}
            onChange={this.handleStandardTableChange}
            loading={loading}
            rowKey={"lineId"}
            size={"small"}
          />
        </div>
      </Card>

    );
  }
}
